from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
#login
from django.contrib import auth
from django.contrib.auth.decorators import login_required
#user creation
from registrationForm import *
#models
from django.contrib.auth.models import User
from solidaridad.game.models import UserProfile
from solidaridad.game.models import *
#times
import datetime
#math functions
import math
#quests forms
from questForm import *

def logout(request):
    auth.logout(request)
    # Redirect to a success page.
    return HttpResponseRedirect("/account/loggedout/")

def mylogout(request):
    #logout(request)
    #return direct_to_template(request, 'logout.html')
    auth.logout(request)
    return HttpResponseRedirect("/login")


@login_required
def welcome_user(request):
    return render_to_response('logged.html')

def login(request):
    username = request.POST.get('username')
    password = request.POST.get('password')
    user = auth.authenticate(username=username, password=password)    
    if user is not None and user.is_active:        
        auth.login(request, user)        
        user.username = user.username.capitalize()
        profile = request.user.get_profile()

        #########################
        #add 5 experience every two minutes #change it later to 1 day
        add_exp_time_based(profile,5,0,0,0,2)
        #########################
        
        ##########################
        #update player level based on EXP points
        generate_user_level(profile,profile.experience)
        ###############################################

        ##############################
        #update the energy of the player every day and a minute
        add_energy_time_based(profile,0,1,0,1)
        ##############################
        
        profile.save()
        usuario = user
	return render_to_response('logged.html', locals())
    else:
        if request.method == 'POST':
            return render_to_response('errorLog.html', locals())
        return render_to_response('login.html', locals())

def no_such_page1(request):
    return render_to_response('nosuchpage.html')

def no_such_page(request,url):
    return render_to_response('nosuchpage.html')

def no_such_page(request,url,secondurl):
    #return render_to_response('nosuchpage.html')
	return HttpResponseRedirect("/no_such_page/")


#register USers
def generateAddUserForm(request):

    if request.method == 'POST':
        form = AddUserForm(request.POST)
        if form.is_valid():

            if not UsernameInDB(form.cleaned_data['username']):
                username = form.cleaned_data['username']                                                
                password = form.cleaned_data['password']

                addUserToDB(form)

            else:
                return render_to_response('register.html', {'form': form, 'userExists': True})

            return render_to_response('confirmRegistration.html', {'username': username,
                                                              'password': password})

    else:
        form = AddUserForm()

    return render_to_response('register.html', {'form': form, 'userExists': False})

def UsernameInDB(username):

    for usr in User.objects.iterator():

        if usr.username == username:
            return True

    return False

def addUserToDB(form):
    user = User.objects.create_user(form.cleaned_data['username'],
                                    '',
                                    form.cleaned_data['password'])    
    user.save()

def editUserForm(request):

    if request.user.id:
        user_db = request.user

        form = registrationForm()

    return render_to_response('editUser.html', {'user':user_db, 'form': form})

def buy_item(request,itemid):
    theItem= Item.objects.get(pk=itemid)    
    if request.user.is_authenticated():
        profile=request.user.get_profile()        
        counter=User_Item.objects.filter(theuser=profile).filter(theitem=theItem).count()        
        if counter >= 1:
            return render_to_response('item_already_bought.html',locals())
        else:
            obj=User_Item(theuser=profile,theitem=theItem)
            obj.save()
            profile.experience+=(theItem.cost/10)
            profile.money-=theItem.cost
            profile.total_energy+=theItem.energy_boost
            profile.save()
            return render_to_response('new_item_bought.html',locals())
    else:
        return render_to_response('items.html',locals())

def view_items(request):   
    all_items=Item.objects.all()
    can_buy=False
    if request.user.is_authenticated():        
        profile = request.user.get_profile()
        name=request.user.username
        my_items=User_Item.objects.filter(theuser=profile)
        can_buy=True        
    return render_to_response('items.html', locals())

def view_my_items(request):
    the_items=Item.objects.all()
    logged=False
    if request.user.is_authenticated():
        logged=True
        profile = request.user.get_profile()
        #name=request.user.username
        my_items=User_Item.objects.filter(theuser=profile)
    return render_to_response('myitems.html', locals())


def view_top10users(request):        
    firstOne=UserProfile.objects.order_by('-experience')[:1]
    total_players=UserProfile.objects.all().count()
    top10_users=UserProfile.objects.order_by('-experience')[0:10]
    logged=False
    if request.user.is_authenticated():
        profile = request.user.get_profile()
        logged=True
    return render_to_response('top_ten.html', locals())


def generate_user_level(this_profile,this_exp):
    this_profile.level= math.floor(this_exp/100)

def add_energy_time_based(who,year_req,day_req,hour_req,min_req):
    before=who.last_seen #date of the last register
    now=datetime.datetime.now()
    who.last_seen=datetime.datetime.now()
    #every day the user logs in ,he gets 5 experience points
    if(( int(str(now.year)) - int(before.year) >= year_req) and ( int(str(now.day)) - int(before.day) >= day_req) and ( int(str(now.hour)) - int(before.hour) >= hour_req) and ( int(str(now.minute)) - int(before.minute) >= min_req)):
        if( before.minute +1  <  int(now.minute)):
           who.energy = who.total_energy
        else:
            who.energy += 0

def add_exp_time_based(who,how_much,year_req,day_req,hour_req,min_req):
    before=who.last_seen #date of the last register
    now=datetime.datetime.now()
    who.last_seen=datetime.datetime.now()
    #every day the user logs in ,he gets 5 experience points
    if(( int(str(now.year)) - int(before.year) >= year_req) and ( int(str(now.day)) - int(before.day) >= day_req) and ( int(str(now.hour)) - int(before.hour) >= hour_req) and ( int(str(now.minute)) - int(before.minute) >= min_req)):
        if( before.minute +1  <  int(now.minute)):
           who.experience += how_much
        else:
            who.experience += 0

def view_developers(request):
    logged=False
    if request.user.is_authenticated():
        logged=True
        profile = request.user.get_profile()
    return render_to_response('developers.html', locals())
    

def view_faq(request):
    logged=False
    if request.user.is_authenticated():
        logged=True
        profile = request.user.get_profile()
    return render_to_response('faq.html', locals())
    

def view_manual(request):
    logged=False
    if request.user.is_authenticated():
        logged=True
        profile = request.user.get_profile()
    return render_to_response('manual.html', locals())

def view_quests(request):
    all_quests=Activity.objects.all()
    can_do=False
    if request.user.is_authenticated():
        profile = request.user.get_profile()
        name=request.user.username
        my_quests=CompletedActivity.objects.filter(theuser=profile)
        can_do=True
    return render_to_response('quests.html', locals())

def view_my_quests(request):
    the_quests=Activity.objects.all()
    logged=False
    if request.user.is_authenticated():
        logged=True
        profile = request.user.get_profile()
        my_quests=CompletedActivity.objects.filter(theuser=profile)
    return render_to_response('myquests.html', locals())


def solve(request,activityid):
    theActivity= Activity.objects.get(pk=activityid)
    theAnswer=theActivity.answer
    logged=False
    if request.user.is_authenticated():
        logged=True
        profile=request.user.get_profile()
        counter=CompletedActivity.objects.filter(theuser=profile).filter(theactivity=theActivity).count()
        if counter >= 1:
            # ALREADY SOLVED
            return render_to_response('activity_already_done.html',locals())
        else:           
            # HASNT BEEN SOLVED
            if request.method == 'POST': # If the form has been submitted...
                form = QuestForm(request.POST) # A form bound to the POST data
                if form.is_valid(): # All validation rules pass
                    #IF CORRECT
                    if(form.cleaned_data['answer']==theAnswer):
                        #########################
                        #add the new CompletedActivity to database and change user stats#
                        obj=CompletedActivity(theuser=profile,theactivity=theActivity)
                        obj.save()
                        profile.experience+=theActivity.experience_reward
                        profile.energy-=theActivity.energy_consumed
                        profile.money+=theActivity.money_reward
                        profile.save()
                        #end changes 
                        #########################
                        # Redirect after POST
                        return render_to_response('correctanswer.html',locals())
                    #IF INCORRECT
                    else:
                        ######################
                        #update user stats. -energy
                        profile.energy-=theActivity.energy_consumed
                        profile.save()
                        # Redirect after POST
                        return render_to_response('incorrect_answer.html',locals())
            else:
                form = QuestForm() # An unbound form

            return render_to_response('do_quest.html', {
                'form': form, 'theActivity': theActivity, 'counter': counter,
                'logged': logged, 'theAnswer': theAnswer, 'profile': profile,})
